//
//  TCoffee.m
//  iBioCAD
//
//  Created by Orbitus on 10/23/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "TCoffee.h"


@implementation TCoffee

- (void) awakeFromNib
{
	[self init];
}

- (id)init {
    self = [super init];
	[[NSNotificationCenter defaultCenter] addObserver:self 
																			  selector:@selector(finishedCoffee:) 
																					 name:NSTaskDidTerminateNotification 
																				   object:nil];
	myTCoffee = nil; // This is a good time to initialize the pointer
	return self;
}

- (IBAction)TCoffee:(id)sender
{
	[tcoffeeButton setTitle:@"Running..."];
	NSLog(@"Running TCoffee...");
    [tcoffeeButton setEnabled:NO];
	
	[appRunningIndicator startAnimation:self];
	
	myTCoffee = [[NSTask alloc] init];
	pipe = [[NSPipe alloc] init];
	NSFileHandle *handle;
	
	//NSLog(@"MOC= %@",[managedObjectContext description]);
	
	
	//take that array and spit each name/sequence as a large fasta file
	//Output this file onto the friendly iBioCAD desktop
	
	myDesktopFolderPath	= @"/Sequences/iBioCAD/Desktop/sequence.fasta";

	tcoffeePath = @"/UnixApps/t_coffee";
	
	[myTCoffee setLaunchPath:tcoffeePath]; 
	
	[myTCoffee setCurrentDirectoryPath:[myDesktopFolderPath stringByDeletingLastPathComponent]];
	[myTCoffee setArguments:[NSArray arrayWithObjects:myDesktopFolderPath,@"-outfile=stdout", nil]];
	[myTCoffee setStandardOutput:pipe];
	
	//	handle=[NSFileHandle fileHandleForReadingAtPath:[myBinFolderPath stringByAppendingPathComponent: @"out.fasta"]];
	
	handle=[pipe fileHandleForReading];
	
	[myTCoffee launch];
	
	//[NSThread detachNewThreadSelector:@selector(copyData:)
	//							 toTarget:self withObject:handle];
	
	//string=[[NSString alloc] initWithData:[handle readDataToEndOfFile]
	//																				   encoding:NSASCIIStringEncoding]; // convert NSData -> NSString
    
    //[tcoffeeOutput setString:string];
	NSLog(@"...Finished TCoffee!");
	
}
- (void)copyData:(NSFileHandle*)handle {
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSData *data;
	
    while([data=[handle availableData] length]) { // until EOF (check reference)
        NSString *string=[[NSString alloc] initWithData:data
																															 encoding:NSASCIIStringEncoding];
        NSRange theEnd=NSMakeRange([[tcoffeeOutput string] length],0);
		
        [tcoffeeOutput replaceCharactersInRange:theEnd
																							 withString:string]; // append new string to the end
        theEnd.location+=[string length]; // the end has moved
        [tcoffeeOutput scrollRangeToVisible:theEnd];
		
        [string release];
    }
	
    [pool release];
}

- (void)finishedCoffee:(NSNotification *)aNotification
{
	//[tcoffeeButton setTitle:@"TCoffee"];
	//[tcoffeeButton setEnabled:YES];
	//[appRunningIndicator stopAnimation:self];
	
	//[myBlast release]; // Don't forget to clean up memory
    //[pipe release];
}

@end

